package com.htstar.ovms.device.service.impl;

import cn.hutool.Hutool;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.ssh.JschUtil;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONConfig;
import cn.hutool.json.JSONUtil;
import com.alibaba.csp.sentinel.util.StringUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.htstar.ovms.admin.api.entity.EtpInfo;
import com.htstar.ovms.admin.api.feign.EtpInfoFeign;
import com.htstar.ovms.admin.api.vo.EtpInfoSVo;
import com.htstar.ovms.common.core.constant.CommonConstants;
import com.htstar.ovms.common.core.util.R;
import com.htstar.ovms.common.data.constant.RedisConstant;
import com.htstar.ovms.common.data.tenant.TenantContextHolder;
import com.htstar.ovms.common.security.service.OvmsUser;
import com.htstar.ovms.common.security.util.SecurityUtils;
import com.htstar.ovms.device.api.constant.AlarmTypeConstant;
import com.htstar.ovms.device.api.dto.*;
import com.htstar.ovms.device.api.entity.CarAlarmMothReport;
import com.htstar.ovms.device.api.entity.DeviceAlarm;
import com.htstar.ovms.device.api.entity.DriverMapAreaCarInfo;
import com.htstar.ovms.device.api.feign.DeviceGpsFeign;
import com.htstar.ovms.device.api.vo.*;
import com.htstar.ovms.device.mapper.DeviceAlarmMapper;
import com.htstar.ovms.device.service.DeviceAlarmService;
import com.htstar.ovms.device.service.GpsService;
import com.htstar.ovms.device.util.Cp;
import com.htstar.ovms.device.util.GpsNewUtil;
import com.htstar.ovms.device.util.PositionUtils;
import com.htstar.ovms.enterprise.api.constant.TimeTypeConstant;
import com.htstar.ovms.enterprise.api.vo.AlarmDataVo;
import com.htstar.ovms.enterprise.api.vo.CarLocationsLatLngVO;
import io.swagger.annotations.ApiModelProperty;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 设备警情
 *
 * @author wj
 * @date 2020-06-12 11:38:07
 */
@Service
@Slf4j
public class DeviceAlarmServiceImpl extends ServiceImpl<DeviceAlarmMapper, DeviceAlarm> implements DeviceAlarmService{

    @Autowired
    private GpsService gpsService;

    @Autowired
    EtpInfoFeign etpInfoFeign;

    @Autowired
    RedisTemplate redisTemplate;

    @Override
    public Page<DeviceAlarmVO> getAlarmInfoByDeviceSnPage(Page page, String deviceSn, String startTime, String endTime, Integer type) {
        return baseMapper.getAlarmInfoByDeviceSnPage(page, deviceSn, startTime, endTime, type);
    }

    @Override
    public DeviceAlarm getEnt(String deviceSn, Long alarmNo, Integer alarmType) {
        return this.baseMapper.getEnt(deviceSn, alarmNo, alarmType);
    }

    @Override
    public Page<CarSecurityAlarmVO> getCarSecurityAlarmPage(CarSecurityAlarmDTO carSecurityAlarmDTO) {
        Integer etpId = TenantContextHolder.getEtpId();
        carSecurityAlarmDTO.setEtpId(etpId);
        Page<CarSecurityAlarmVO> carSecurityAlarmPage = baseMapper.getCarSecurityAlarmPage(carSecurityAlarmDTO);
        for (CarSecurityAlarmVO record : carSecurityAlarmPage.getRecords()) {
            int unRead = 0, totalAlarm = 0;
            LocalDateTime DateTime = null;
            String deviceSn = record.getDeviceSn();
            if (StringUtils.isNotBlank(deviceSn)) {
                //unRead = count(new QueryWrapper<DeviceAlarm>().eq("device_sn", deviceSn).eq("is_read", "0").eq("is_del",0));
                totalAlarm = count(new QueryWrapper<DeviceAlarm>().eq("device_sn", deviceSn));
                DateTime = baseMapper.getLastTestTime(deviceSn);
            }
            //record.setUnRead(unRead);
            record.setTotalAlarm(totalAlarm);
            record.setLastDateTime(DateTime);
        }
        return carSecurityAlarmPage;
    }

    @Override
    public Page<DeviceAlarmVO> getAlarmByTypeAndTimePage(CarSecurityAlarmDTO carSecurityAlarmDTO) {
        if (carSecurityAlarmDTO.getEtpId() == null) {
            carSecurityAlarmDTO.setEtpId(SecurityUtils.getUser().getEtpId());
        }
        List<EtpInfoSVo> currentAndParents1 = etpInfoFeign.getCurrentAndParents1(carSecurityAlarmDTO.getEtpId());
        currentAndParents1.forEach(etpInfoSVo -> {
            carSecurityAlarmDTO.setEtpIds(etpInfoSVo.getIds());
        });
        Page<DeviceAlarmVO> alarmByTypeAndTimePage = baseMapper.getAlarmByTypeAndTimePage(carSecurityAlarmDTO);
        Integer alarmByTypeCounts = baseMapper.getAlarmByTypeCounts(Cp.cp(carSecurityAlarmDTO, new CarSecurityAlarmCountDTO()));
        //重新替换总数避免查询总数
        alarmByTypeAndTimePage.setTotal(alarmByTypeCounts);
//        //在外面用流进行排序避免数据库排序使索引失效
//        List<DeviceAlarmVO> collect = alarmByTypeAndTimePage
//                .getRecords()
//                .stream()
//                .sorted(Comparator.comparing(DeviceAlarmVO::getStaTime).reversed())//倒序
//                .collect(Collectors.toList());
//        alarmByTypeAndTimePage.setRecords(collect);
        return alarmByTypeAndTimePage;

    }
    @Override
    public List<DeviceAlarmVO> getAlarmByTypeAndTimeList(CarSecurityAlarmDTO carSecurityAlarmDTO) {
        CarSecurityAlarmListDTO cp = Cp.cp(carSecurityAlarmDTO, new CarSecurityAlarmListDTO());
        if (!Objects.equals(carSecurityAlarmDTO.getId(), null) && !Objects.equals(carSecurityAlarmDTO.getId(), "")) {
            int[] objects = Arrays.stream(carSecurityAlarmDTO.getId().split(","))
                    .mapToInt(s -> Integer.parseInt(s)).toArray();
            cp.setId(objects);
        }
        if (carSecurityAlarmDTO.getEtpId() == null) {
            carSecurityAlarmDTO.setEtpId(SecurityUtils.getUser().getEtpId());
        }
        List<EtpInfoSVo> currentAndParents1 = etpInfoFeign.getCurrentAndParents1(carSecurityAlarmDTO.getEtpId());
        currentAndParents1.forEach(etpInfoSVo -> {
            cp.setEtpIds(etpInfoSVo.getIds());
        });
        return baseMapper.getAlarmByTypeAndTimeList(cp);
    }

    /**
     * 获取企业id
     *
     * @param deviceDTO
     */

    private void getEtpId(CarSecurityAlarmDTO deviceDTO) {
        OvmsUser user = SecurityUtils.getUser();
        if (deviceDTO.getEtpId() == null && user != null) {
            if (user.getEtpId() != CommonConstants.ETP_ID_1) {
                deviceDTO.setEtpId(user.getEtpId());
            }
        }
    }

    /**
     * 获取企业id
     *
     * @param deviceDTO
     */
    private void getEtpId(CarSecurityAlarmListDTO deviceDTO) {
        OvmsUser user = SecurityUtils.getUser();
        if (deviceDTO.getEtpId() == null && user != null) {
            if (user.getEtpId() != CommonConstants.ETP_ID_1) {
                deviceDTO.setEtpId(user.getEtpId());
            }
        }
    }

    @Override
    public Page<MonitoringVO> getMonitoringPage(MonitoringDTO monitoringDTO) {
//        OvmsUser userCurr = SecurityUtils.getUser();
//        Integer etpId = userCurr.getEtpId();
//        //获取其下所有企业
//        R etpTreeNoDept = etpInfoFeign.getEtpTreeNoDeptHsl(etpId);
//        List curEtp = (List) etpTreeNoDept.getData();
//        Map o = (Map) curEtp.get(0);
//        List ids = (List) o.get("ids");//得到该企业下所有子企业idList
//        ids.add(etpId);
//        monitoringDTO.setEtpIds(ids);
        //打开页面时未传EtpId。自动获取
        if (CollectionUtils.isEmpty(monitoringDTO.getEtpIds())) {
            OvmsUser user = SecurityUtils.getUser();
//            if (user.getEtpId() != CommonConstants.ETP_ID_1) {
//                list.add(user.getEtpId());
//                monitoringDTO.setEtpIds(list);
//            }
            ArrayList<Integer> list = new ArrayList<>();
            list.add(user.getEtpId());
            monitoringDTO.setEtpIds(list);
        }
        ArrayList<Integer> sons = new ArrayList<>();
        for (Integer id : monitoringDTO.getEtpIds()) {
            List<EtpInfoSVo> currentAndParents1 = etpInfoFeign.getCurrentAndParents1(id);
            EtpInfoSVo etpInfoSVo = currentAndParents1.get(0);
            List<Integer> ids = etpInfoSVo.getIds();
//            List<Integer> rs = baseMapper.getDescendantForEtpId(id);
            sons.addAll(ids);
        }
        monitoringDTO.getEtpIds().addAll(sons);

        Page<MonitoringVO> page = baseMapper.getMonitoringPage(monitoringDTO);
        for (MonitoringVO record : page.getRecords()) {
            //解析地址
            if (null != record.getLat() && null != record.getLng()) {
                //坐标转换
                double[] doubles = GpsNewUtil.toGCJ02Point(record.getLat(), record.getLng(), 5);
//                latAndLngVO.setLat(doubles[0]);
//                latAndLngVO.setLng(doubles[1]);
//                String gpsAddr = gpsService.getGpsAddr(doubles[0], doubles[1]);
                String gpsAddr = gpsService.getGpsAddr(record.getLat(), record.getLng());
                record.setAddr(gpsAddr);
            }

            //解析方向
            if (null != record.getDirection()) {
                String deretion = PositionUtils.getDeretion(record.getDirection());
                record.setOrientation(deretion);
            }
            if (record.getPull() == null) {
                record.setPull(0);
            }
            boolean a = record.getPull().equals(1) && record.getOnline().equals(0);//pull==1&&online==0
            boolean b = record.getPull().equals(1) && record.getOnline().equals(3);//pull==1&&online==3
            if (a || b) {
                record.setOnline(2); //这两种状态online==2
            }
        }
        page.getRecords().stream().map(record -> {
            //解析地址
            if (null != record.getLat() && null != record.getLng()) {
                //坐标转换
                double[] doubles = GpsNewUtil.toGCJ02Point(record.getLat(), record.getLng(), 5);
//                latAndLngVO.setLat(doubles[0]);
//                latAndLngVO.setLng(doubles[1]);
//                String gpsAddr = gpsService.getGpsAddr(doubles[0], doubles[1]);
                String gpsAddr = null;
                try {
                    gpsAddr = gpsService.getGpsAddr(record.getLat(), record.getLng());
                } catch (Exception e) {
                    e.printStackTrace();
                    return R.failed("地理位置解析失败");
                }
                record.setAddr(gpsAddr);
            }

            //解析方向
            if (null != record.getDirection()) {
                String deretion = PositionUtils.getDeretion(record.getDirection());
                record.setOrientation(deretion);
            }
            if (record.getPull() == null) {
                record.setPull(0);
            }

            boolean a = record.getPull().equals(1) && record.getOnline().equals(0);//pull==1&&online==0
            boolean b = record.getPull().equals(1) && record.getOnline().equals(3);//pull==1&&online==3
            if (a || b) {
                record.setOnline(2); //这两种状态online==2
            }
            return null;
        });
        return page;
    }

    @Override
    public MonitoringLatLngCountVO getMonitorings(MonitoringLatLngDTO monitoringDTO) {
        MonitoringLatLngCountVO vos = new MonitoringLatLngCountVO();
        int count1 = 0;
        int count2 = 0;
        if (CollectionUtils.isEmpty(monitoringDTO.getEtpIds())) {
            OvmsUser user = SecurityUtils.getUser();
            ArrayList<Integer> list = new ArrayList<>();
//            if (user.getEtpId() != CommonConstants.ETP_ID_1) {
//                list.add(user.getEtpId());
//                monitoringDTO.setEtpIds(list);
//            }
            list.add(user.getEtpId());
            monitoringDTO.setEtpIds(list);
        }
        ArrayList<Integer> sons = new ArrayList<>();
        for (Integer id : monitoringDTO.getEtpIds()) {
            List<EtpInfoSVo> currentAndParents1 = etpInfoFeign.getCurrentAndParents1(id);
            EtpInfoSVo etpInfoSVo = currentAndParents1.get(0);
            List<Integer> ids = etpInfoSVo.getIds();
//            List<Integer> rs = baseMapper.getDescendantForEtpId(id);
            sons.addAll(ids);
        }
        monitoringDTO.getEtpIds().addAll(sons);

        List<MonitoringLatLngVO> list = baseMapper.getMonitorings(monitoringDTO);
//        for (MonitoringLatLngVO record : list) {
//            //解析地址
//            if (null != record.getLat() && null != record.getLng()) {
//                //坐标转换
//                double[] doubles = GpsNewUtil.toGCJ02Point(record.getLat(), record.getLng(), 5);
////                latAndLngVO.setLat(doubles[0]);
////                latAndLngVO.setLng(doubles[1]);
////                String gpsAddr = gpsService.getGpsAddr(doubles[0], doubles[1]);
////                String gpsAddr = gpsService.getGpsAddr(doubles[0], doubles[1]);
////                record.setAddr(gpsAddr);
//                record.setLat(doubles[0]);
//                record.setLng(doubles[1]);
////
////                String gpsAddr = gpsService.getGpsAddr(record.getLat(), record.getLng());
////                record.setAddr(gpsAddr);
//            }
//            //解析方向
//            if (null != record.getDirection()) {
//                String deretion = PositionUtils.getDeretion(record.getDirection());
//                record.setOrientation(deretion);
//            }
//        }

//        for (int i = 0; i < list.size(); i++) {
//            MonitoringLatLngVO vo = list.get(i);
//            if (vo.getOnline() != null && vo.getOnline() == 1) {
//                vo.getOnline();
//                count1++;
//            }
//            if (vo.getOnline() != null && vo.getOnline() == 0) {
//                vo.getOnline();
//                count2++;
//            }
//        }

        Map<Integer, List<MonitoringLatLngVO>> collect = list.stream().filter(item -> item.getOnline() == 0 || item.getOnline() == 1)
                .collect(Collectors.groupingBy(MonitoringLatLngVO::getOnline));
        vos.setMonitoringLatLngVOS(list);
        if (collect.get(1) != null) {
            vos.setCountCarStatus(collect.get(1).size());
        }
        if (collect.get(0) != null) {
            vos.setCountCarSends(collect.get(0).size());
        }
        return vos;
    }

    @Override
    public List<MonitoringVO> exportLocationInfo(ExportMonitoringDTO monitoringDTO) {
        OvmsUser user = SecurityUtils.getUser();
//        if (monitoringDTO.getEtpId() == -1 && user != null) {
//            if (user.getEtpId() != CommonConstants.ETP_ID_1) {
        monitoringDTO.setEtpId(user.getEtpId());
//            }
//        }
        return baseMapper.exportLocationInfo(monitoringDTO);
    }

    /**
     * 获取企业警情数据
     *
     * @param etpId
     * @param dateTime
     * @return
     */
    @Override
    public AlarmDataVo getAlarmDataByEtpId(Integer etpId, String dateTime) {

        //********T***********
//        redisTemplate.delete(RedisConstant.etpIdsTree);
//
//        List<Integer> integers = new ArrayList<>();
//        integers.add(1);
//        integers.add(64);
//        //放缓存
//        JSONArray array222 = JSONUtil.createArray();
//        array222.addAll(integers);
//        String done222 = array222.toString();
//        redisTemplate.opsForHash().put(RedisConstant.etpIdsTree, RedisConstant.getAlarmDataByEtpId_prefix + etpId,
//                done222);
        //********T***********

        Boolean isCache = redisTemplate.opsForHash().hasKey(RedisConstant.etpIdsTree, RedisConstant.getAlarmDataByEtpId_prefix + etpId);
        EtpInfoSVo etpInfoSVo = null;
        List<Integer> etpIds = null;
        if (isCache) {
            String etpIdsTreeStr = (String) redisTemplate.opsForHash().get(RedisConstant.etpIdsTree, RedisConstant.getAlarmDataByEtpId_prefix + etpId);
            JSONArray jsonArray = JSONUtil.parseArray(etpIdsTreeStr);
            etpIds = jsonArray.toList(Integer.class);
        } else {//没有缓存
            List<EtpInfoSVo> currentAndParents1 = etpInfoFeign.getCurrentAndParents1(etpId);
            etpInfoSVo = currentAndParents1.get(0);
            etpIds = etpInfoSVo.getIds();
            etpIds.add(etpId);
            //放缓存
            JSONArray array = JSONUtil.createArray();
            array.addAll(etpIds);

            String done = array.toString();
            redisTemplate.opsForHash().put(RedisConstant.etpIdsTree, RedisConstant.getAlarmDataByEtpId_prefix + etpId,
                    done);
        }


        Date date = DateUtil.parse(dateTime);
        AlarmDataVo vo = new AlarmDataVo();
        List<DeviceAlarm> list = baseMapper.getAlarmDataByEtpId(etpIds, date);
//        baseMapper.selectList()
        if (CollUtil.isNotEmpty(list)) {
            for (DeviceAlarm deviceAlarm : list) {
                //数量
                Integer alarmCount = deviceAlarm.getAlarmCount();
                //类型
                Integer alarmType = deviceAlarm.getAlarmType();
                switch (alarmType) {
                    case AlarmTypeConstant.ACCELERATE://4
                        vo.setAccelerate(alarmCount);
                        break;
                    case AlarmTypeConstant.DECELERATE://5
                        vo.setDecelerate(alarmCount);
                        break;
                    case AlarmTypeConstant.TURN_AROUND://12
                        vo.setTurnAround(alarmCount);
                        break;
                    case AlarmTypeConstant.SPEEDING://1
                        vo.setSpeeding(alarmCount);
                        break;
                    case AlarmTypeConstant.PULL_OUT://14
                        vo.setPullOut(alarmCount);
                        break;
                    case AlarmTypeConstant.LOW_BATTERY://2
                        vo.setLowBattery(alarmCount);
                        break;
                    case AlarmTypeConstant.TOW://7
                        vo.setTow(alarmCount);
                        break;
                    case AlarmTypeConstant.IGNITION://22
                        vo.setIgnition(alarmCount);
                        break;
                    case AlarmTypeConstant.WATER_TEMP://3
                        vo.setWaterTemp(alarmCount);
                        break;
                    case AlarmTypeConstant.MALFUNCTION://24
                        vo.setMalfunction(alarmCount);
                        break;
                    case AlarmTypeConstant.COLLISION://17
                        vo.setCollision(alarmCount);
                        break;
                    case AlarmTypeConstant.FENCE://29
                        vo.setFence(alarmCount);
                        break;
                    default:
                        break;
                }

            }
        }
        return vo;
    }

    /**
     * 查询地图
     *
     * @param area
     * @return
     */
    @Override
    public List<AreaVo> findList(AreaDTO area) {
        return baseMapper.findList(area);
    }

    /**
     * 查询地图阶梯式
     *
     * @param
     * @return
     */
    @Override
    public List<AreaListVo> findLists() {
        return baseMapper.findLists();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public AlarmDataVo getAlarmDataMultiEtp(Integer etpIdFrom, String dateTime) {
        List<EtpInfoSVo> currentAndParents1 = etpInfoFeign.getCurrentAndParents1(etpIdFrom);
        EtpInfoSVo etpInfoSVo = currentAndParents1.get(0);
        List<Integer> etpIds = etpInfoSVo.getIds();
        etpIds.add(etpIdFrom);
        List<Integer> collect = etpIds.stream().distinct().collect(Collectors.toList());
        ArrayList<AlarmDataVo> voList = new ArrayList<>();
        for (Integer etpId : collect) {
            AlarmDataVo vo = new AlarmDataVo();
            Date date = DateUtil.parse(dateTime);
//            List<DeviceAlarm> list = baseMapper.getAlarmDataByEtpId(etpId, date);
//            if (CollUtil.isNotEmpty(list)) {
//                for (DeviceAlarm deviceAlarm : list) {
//                    //数量
//                    Integer alarmCount = deviceAlarm.getAlarmCount();
//                    //类型
//                    Integer alarmType = deviceAlarm.getAlarmType();
//                    switch (alarmType) {
//                        case AlarmTypeConstant.ACCELERATE://4
//                            vo.setAccelerate(alarmCount);
//                            break;
//                        case AlarmTypeConstant.DECELERATE://5
//                            vo.setDecelerate(alarmCount);
//                            break;
//                        case AlarmTypeConstant.TURN_AROUND://12
//                            vo.setTurnAround(alarmCount);
//                            break;
//                        case AlarmTypeConstant.SPEEDING://1
//                            vo.setSpeeding(alarmCount);
//                            break;
//                        case AlarmTypeConstant.PULL_OUT://14
//                            vo.setPullOut(alarmCount);
//                            break;
//                        case AlarmTypeConstant.LOW_BATTERY://2
//                            vo.setLowBattery(alarmCount);
//                            break;
//                        case AlarmTypeConstant.TOW://7
//                            vo.setTow(alarmCount);
//                            break;
//                        case AlarmTypeConstant.IGNITION://22
//                            vo.setIgnition(alarmCount);
//                            break;
//                        case AlarmTypeConstant.WATER_TEMP://3
//                            vo.setWaterTemp(alarmCount);
//                            break;
//                        case AlarmTypeConstant.MALFUNCTION://24
//                            vo.setMalfunction(alarmCount);
//                            break;
//                        case AlarmTypeConstant.COLLISION://17
//                            vo.setCollision(alarmCount);
//                            break;
//                        case AlarmTypeConstant.FENCE://29
//                            vo.setFence(alarmCount);
//                            break;
//                        default:
//                            break;
//                    }
//                }
//            }
//            voList.add(vo);
        }
        //数据整合
        AlarmDataVo voSum = new AlarmDataVo();
        for (AlarmDataVo vo : voList) {
            voSum.setAccelerate(voSum.getAccelerate() + vo.getAccelerate());
            voSum.setDecelerate(voSum.getDecelerate() + vo.getDecelerate());
            voSum.setTurnAround(voSum.getTurnAround() + vo.getTurnAround());
            voSum.setSpeeding(voSum.getSpeeding() + vo.getSpeeding());
            voSum.setPullOut(voSum.getPullOut() + vo.getPullOut());
            voSum.setLowBattery(voSum.getLowBattery() + vo.getLowBattery());
            voSum.setTow(voSum.getTow() + vo.getTow());
            voSum.setIgnition(voSum.getIgnition() + vo.getIgnition());
            voSum.setWaterTemp(voSum.getWaterTemp() + vo.getWaterTemp());
            voSum.setMalfunction(voSum.getMalfunction() + vo.getMalfunction());
            voSum.setCollision(voSum.getCollision() + vo.getCollision());
            voSum.setFence(voSum.getFence() + vo.getFence());
        }
        return voSum;
    }

    @Override
    public void saveOnlineReport(CarAlarmMothReport carAlarmMothReport) {
        baseMapper.saveOnlineReport(carAlarmMothReport);
    }

    @Override
    public Integer getAlarmByTypeAndTimeListCount(CarSecurityAlarmDTO carSecurityAlarmDTO) {
        CarSecurityAlarmListDTO cp = Cp.cp(carSecurityAlarmDTO, new CarSecurityAlarmListDTO());
        if (!Objects.equals(carSecurityAlarmDTO.getId(), null) && !Objects.equals(carSecurityAlarmDTO.getId(), "")) {
            int[] objects = Arrays.stream(carSecurityAlarmDTO.getId().split(","))
                    .mapToInt(s -> Integer.parseInt(s)).toArray();
            cp.setId(objects);
        }
//        if (carSecurityAlarmDTO.getEtpId() == null) carSecurityAlarmDTO.setEtpId(SecurityUtils.getUser().getEtpId());
//        List<EtpInfoSVo> currentAndParents1 = etpInfoFeign.getCurrentAndParents1(carSecurityAlarmDTO.getEtpId());
//        currentAndParents1.forEach(etpInfoSVo -> {
//            carSecurityAlarmDTO.setEtpIds(etpInfoSVo.getIds());
//        });
        cp.setEtpIds(carSecurityAlarmDTO.getEtpIds());
        return baseMapper.getAlarmByTypeAndTimeCount(cp);
    }

    @Override
    public List<DeviceAlarmExcelVO> getAlarmByTypeAndTimeListForExcel(CarSecurityAlarmDTO carSecurityAlarmDTO) {
        CarSecurityAlarmListDTO cp = Cp.cp(carSecurityAlarmDTO, new CarSecurityAlarmListDTO());
        if (!Objects.equals(carSecurityAlarmDTO.getId(), null) && !Objects.equals(carSecurityAlarmDTO.getId(), "")) {
            int[] objects = Arrays.stream(carSecurityAlarmDTO.getId().split(","))
                    .mapToInt(s -> Integer.parseInt(s)).toArray();
            cp.setId(objects);
        }
        cp.setEtpIds(carSecurityAlarmDTO.getEtpIds());

        return baseMapper.getAlarmByTypeAndTimeCountForExcel(cp);

    }

    @Override
    public R getAlarmDataDirect(Integer timeType, EtpInfo etpInfo) {
        OvmsUser user = SecurityUtils.getUser();
        Integer etpId = user.getEtpId();
        if (etpInfo.getId() != null) {
            etpId = etpInfo.getId();
        }
        Date date = this.getDate(timeType);
        String s = DateUtil.formatDateTime(date);
        AlarmDataVo alarmDataByEtpId = getAlarmDataByEtpId(etpId, s);
        return R.ok(alarmDataByEtpId);
    }

    private Date getDate(Integer timeType) {
        //当天的开始时间
        Date date = DateUtil.beginOfDay(DateUtil.date());
        if (timeType == TimeTypeConstant.SEVEN_DAY) {
            date = DateUtil.offsetDay(date, -7);
        }
        if (timeType == TimeTypeConstant.FIFTEEN_DAY) {
            date = DateUtil.offsetDay(date, -15);
        }
        if (timeType == TimeTypeConstant.THIRTY_DAY) {
            date = DateUtil.offsetDay(date, -30);
        }
        if (timeType == TimeTypeConstant.THREE_MONTHS) {
            date = DateUtil.offsetMonth(date, -3);
        }
        if (timeType == TimeTypeConstant.SIX_MONTHS) {
            date = DateUtil.offsetMonth(date, -6);
        }
        if (timeType == TimeTypeConstant.ONE_YEAR) {
            date = DateUtil.offset(date, DateField.YEAR, -1);
        }
        return date;
    }

}
